package com.terry.gamesupport.sms.service.impl;

import com.rabbitmq.client.Channel;
import lombok.ToString;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.EnableRabbit;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.terry.common.utils.PageUtils;
import com.terry.common.utils.Query;

import com.terry.gamesupport.sms.dao.AttachmentDao;
import com.terry.gamesupport.sms.entity.AttachmentEntity;
import com.terry.gamesupport.sms.service.AttachmentService;


@Service("attachmentService")
@EnableRabbit
@ToString
public class AttachmentServiceImpl extends ServiceImpl<AttachmentDao, AttachmentEntity> implements AttachmentService {

    @Autowired
    RabbitTemplate rabbitTemplate;

    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttachmentEntity> page = this.page(
                new Query<AttachmentEntity>().getPage(params),
                new QueryWrapper<AttachmentEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 参数可以写一下类型
     * 1.Message message:原生消息详细信息。 头+体
     * 2.发送的消息类型
     *
     * @param message
     */
    @RabbitListener(queues = {"order.release.order.queue"})
    public void receiveMessage(Message message, AttachmentEntity attachmentEntity, Channel channel) throws Exception{
        //消费端确认机制
        //1.默认自动确认，消息接收到，就自动移除
        //问题收到很多消息，服务器宕机消息丢失
        //手动确认
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        //签收，非批量模式
        logger.info("接收到附件消息",attachmentEntity);
        //TODO 如果附件没被绑定就进行删除
        try {
            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            //拒收消息，非批量模式,消息再入队
            channel.basicNack(deliveryTag,false,true);
            //拒绝签收,消息再入队
            channel.basicReject(deliveryTag,true);
        }
    }

}